<template>
	<div class="p-0">
		<n-card>
			<div class="flex justify-between">
				<div>
					<n-space>
						<n-button @click="initData" type="primary">
							<template #icon>
								<n-icon :component="reloadIcon"></n-icon>
							</template>
							刷新
						</n-button>
						<n-button v-if="checkedRowKeys.length" @click="batchActionDelete" ghost type="error">
							<template #icon>
								<n-icon :component="removeIcon"></n-icon>
							</template>
							删除
						</n-button>
					</n-space>
				</div>
				<div>
					<n-button type="primary" @click="openModal">
						<template #icon>
							<n-icon :component="addIcon"></n-icon>
						</template>
						添加
					</n-button>
				</div>
			</div>
			<div class="mt-3">
				<n-data-table :columns="columns"
				              remote
				              :data="data"
				              :loading="tableLoading"
				              :pagination="pagination"
				              :row-key="(row: any) => row.id"
				              @update:page="handlePageChange"
				              @update:page-size="handlePageSizeChange"
				              v-model:checked-row-keys="checkedRowKeys" />
			</div>
		</n-card>
		
		<n-modal v-model:show="showModal" transform-origin="center" :on-after-leave="closeModal" :mask-closable="false">
			<n-card
				style="width: 600px"
				:title="(isEdit ? '修改' : '添加') +'管理员'"
				closable
				@close="closeModal">
				<n-form
					ref="formRef"
					:label-width="80"
					:model="formValue"
					:rules="rules"
					label-placement="left"
					label-width="auto"
				>
					<n-form-item label="用户名" path="name">
						<n-input v-model:value="formValue.name" placeholder="输入用户名" />
					</n-form-item>
					<n-form-item label="登录账号" path="username">
						<n-input v-model:value="formValue.username" placeholder="输入用户名" />
					</n-form-item>
					<n-form-item label="密码" path="password">
						<n-input type="password"
						         show-password-on="mousedown"
						         v-model:value="formValue.password"
						         placeholder="输入密码" />
					</n-form-item>
					<n-form-item label="头像" path="avatar_id">
						<n-input type="number" v-model:value="formValue.avatar_id" placeholder="输入密码" />
					</n-form-item>
					<n-form-item label="角色" path="roles">
						<n-select multiple :options="roleOptions" v-model:value="formValue.roles"></n-select>
					</n-form-item>
				</n-form>
				<template #footer>
					<div class="flex justify-end">
						<n-button ghost class="mr-5" @click="closeModal">取 消</n-button>
						<n-button type="primary" @click="submit">提 交</n-button>
					</div>
				</template>
			</n-card>
		</n-modal>
	</div>
</template>

<script lang="ts" setup>
import {h, reactive, ref} from "vue"
import {NTag, NTime, useDialog, useMessage} from "naive-ui"
import {rowDeleteButton, rowEditButton} from "@/utils/button"
import {systemAdmin as request} from "@/api/api"
import {ionicons5Icon} from "@/utils/icon"

const addIcon = ionicons5Icon("Add")
const removeIcon = ionicons5Icon("RemoveCircleOutline")
const reloadIcon = ionicons5Icon("ReloadOutline")

const message = useMessage()
const dialog = useDialog()

// 表格加载动画
const tableLoading = ref(false)

// 选中行数据
const checkedRowKeys = ref([])

// 表格列
const columns = [
	{
		type: "selection",
	},
	{
		title: "ID",
		key: "id",
	},
	{
		title: "用户名",
		key: "name",
	},
	{
		title: "登录账号",
		key: "username",
	},
	{
		title: "角色",
		key: "roles",
		render(row: any) {
			return row.roles.map((item: any) => {
				return h(
					NTag,
					{
						style: {
							marginRight: "6px",
						},
						type: "primary",
					},
					{
						default: () => item.name,
					},
				)
			})
		},
	},
	{
		title: "创建时间",
		key: "created_at",
	},
	{
		title: "操作",
		key: "actions",
		width: 260,
		flexd: "right",
		render(row: unknown) {
			return [
				rowEditButton(rowActionEdit, row),
				rowDeleteButton(rowActionDelete, row),
			]
		},
	},
]

// 当前页
let currentPage = 1
// 每页数量
let pageSize = 15
// 总条数
let total = 0

// 分页
const pagination = reactive<any>({
	pageSize: pageSize,
	itemCount: 0,
	pageSizes: [15, 20, 30, 50, 100, 200],
	showSizePicker: true,
	showQuickJumper: true,
	prefix: () => {
		return `共 ${pagination.itemCount} 条`
	},
})

const data = ref([])
// 表格数据
const initData = () => {
	tableLoading.value = true
	
	let params = {
		page: currentPage,
		page_size: pageSize,
	}
	
	request.list(params).then((res) => {
		data.value = res.data.list
		
		pagination.page = res.data.page
		pagination.itemCount = res.data.total
		pagination.pageSize = res.data.page_size
		
		tableLoading.value = false
	})
}
initData()

const handlePageChange = (page: number) => {
	currentPage = page
	initData()
}

const handlePageSizeChange = (size: number) => {
	pageSize = size
	initData()
}

// 新增/编辑
const formRef = ref<any>(null)
// 编辑
let isEdit = ref(false)

const formValue = ref({
	username: "",
	password: "",
	name: "",
	avatar_id: <number>0,
	roles: <any>[],
})

const rules = {
	name: {
		required: true,
		message: "请输入用户名",
		trigger: "input",
	},
	username: {
		required: true,
		message: "请输入登录账号",
		trigger: "input",
	},
	password: {
		required: true,
		message: "请输入密码",
		trigger: "input",
	},
}

const methodOptions = [
	{value: "ANY", label: "ANY"},
	{value: "GET", label: "GET"},
	{value: "POST", label: "POST"},
	{value: "PUT", label: "PUT"},
	{value: "DELETE", label: "DELETE"},
]

const showModal = ref(false)

const roleOptions = ref([])

request.roles().then((res) => {
	roleOptions.value = res.data
})

// 打开模态窗
const openModal = () => {
	showModal.value = true
}

// 模态窗关闭并清空表单
const closeModal = () => {
	showModal.value = false
	isEdit.value = false
	
	formValue.value = {
		username: "",
		password: "",
		name: "",
		avatar_id: 0,
		roles: <any>[],
	}
}

// 提交表单
const submit = (e: MouseEvent) => {
	e.preventDefault()
	formRef.value?.validate((errors: unknown) => {
		if (!errors) {
			if (isEdit.value) {
				request.update(formValue.value).then((res: any) => {
					if (res.code == 200) {
						message.success(res.message)
						closeModal()
						initData()
					} else {
						message.error(res.message)
					}
				})
			} else {
				request.store(formValue.value).then((res: any) => {
					if (res.code == 200) {
						message.success(res.message)
						closeModal()
						initData()
					} else {
						message.error(res.message)
					}
				})
			}
		}
	})
}

// 修改
const rowActionEdit = (row: any) => {
	isEdit.value = true
	request.find(row.id).then((res: any) => {
		formValue.value = res.data
		let roles = res.data.roles
		formValue.value.roles = roles.map((item: any) => {
			return item.id
		})
		
		openModal()
	})
}

// 删除
const rowActionDelete = (row: any) => {
	request.delete(row.id.toString()).then((res: any) => {
		if (res.code == 200) {
			message.success(res.message)
			initData()
		} else {
			message.error(res.message)
		}
	})
}

// 批量
const batchActionDelete = () => {
	dialog.warning({
		title: "提示",
		content: "该操作不可逆, 是否继续？",
		positiveText: "确定",
		negativeText: "取消",
		onPositiveClick: () => {
			let ids = checkedRowKeys.value
			request.delete(ids.join(",")).then((res: any) => {
				if (res.code == 200) {
					message.success(res.message)
					checkedRowKeys.value = []
					initData()
				} else {
					message.error(res.message)
				}
			})
		},
	})
}
</script>
